﻿using System.Collections.Generic;
using Common;
using ImageProcessing.Common;
using ImageProcessing.Descriptors;
using ImageProcessing.Detectors;
using ImageProcessing.Matchers;

namespace ImageProcessing.Engine
{
    public class OnlineImageProcessingEngine : BaseImageProcessingEngine
    {
        private readonly IMatcher _matcher = new HandlerNearestNeighbour();

        private PointsResultProcessor _prp;

        public OnlineImageProcessingEngine(DetectorType detectorType = DetectorType.FastCorner)
            : base(detectorType)
        {
        }

        public PointsResultProcessor MatchPoints(List<InterestPoint> interestPoints)
        {
            _prp = new PointsResultProcessor(MinFoundPoints, interestPoints, _matcher, null);
            _prp.ProcessPoints();

            return _prp;
        }

        public void Initialise()
        {
            List<InterestPoint> loadedPoints = DBConnection.LoadAllPoints();
            _matcher.ImportPoints(loadedPoints);
        }

        public override void Dispose()
        {
            
        }

        public List<InterestPoint> LearnImage(TagInfo tagInfo, int width, int height, ref int[] argbData, ref byte[] yData)
        {
            IInterestPointDetector ipd = BuildDetector(_detectType, width, height);
            List<InterestPoint> points = null;

            if (argbData != null && argbData.Length > 0)
                points = ipd.GetInterestPoints(ref argbData);

            if (yData != null && yData.Length > 0)
                points = ipd.GetInterestPoints(ref yData);

            SurfDescriptor.DecribeInterestPoints(points, false, false, ipd.IntegralImage, tagInfo);
            List<InterestPoint> pointsLearnt = _matcher.Train(points);

            DBConnection.SavePoints(tagInfo, pointsLearnt);

            return pointsLearnt;
        }
    }
}
